package net.blogjava.mobile;

import java.io.File;
import net.blogjava.mobile.widget.FileBrowser;
import net.blogjava.mobile.widget.OnFileBrowserListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.content.BroadcastReceiver;
import android.os.storage.StorageManager;
import android.os.storage.StorageEventListener;
import android.util.Log;
import android.view.Display;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.AbsListView.LayoutParams;
		
public class Main extends Activity implements OnFileBrowserListener {
	private String leftPad = "          Path: ";

	public String sizeStr;
	public String dateStr;

	public TextView fileSize;
	public TextView fileDate;
	public ImageView imgFile;
//
	private FileBrowser fileBrowser;
	private String currentFilePath;
	
	private StorageManager mStorageManager = null;

	static final String LANRES = "com.pclink.lan.res.msg";
	private static final int POSTER_DATA_0 = 0;
	private static final int POSTER_DATA_1 = 1;
	private static final int POSTER_DATA_2 = 2;
	private static final int POSTER_DATA_10 = 10;
	private static final int POSTER_DATA_11 = 11;
	private static final int POSTER_DATA_12 = 12;
	private static final int POSTER_DATA_13 = 13;
	private static final int POSTER_LANSCAN_FAIL = 21;
	public static int lanError = -1;
	public static int lanOpStatusSucceed = 0;
	public static int lanOpStatusFail = 1;
	public static int lanOpStatusInprogress = 2;
	public static int lanOpStatusErrNoError = 10;
	public static int lanOpStatusErrWrongPassword = 11;
	public static int lanOpStatusErrSystem = 12;
	public static int lanOpStatusErrNetworkConnection = 13;
	public int lanOpStatus = lanError;
	public String cmd="";

	private final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			fileBrowser.allowLanScan = true;
			switch (msg.what) {
				case POSTER_DATA_0:
					Log.d("===POSTER_DATA_0===","xujm");
					fileBrowser.needLanScan = false;
					fileBrowser.goPausedDirectory();
					break;
				case POSTER_LANSCAN_FAIL:
					Log.d("===POSTER_LANSCAN_FAIL===","xujm");
					fileBrowser.needLanScan = true;
					break;
				case POSTER_DATA_1:
					Log.d("===POSTER_DATA_1===","xujm");
					fileBrowser.lanPath = "";
					break;
				case POSTER_DATA_2:
					Log.d("===POSTER_DATA_2===","xujm");
					break;
				case POSTER_DATA_10:
					Log.d("===POSTER_DATA_10===","xujm");
					break;
				case POSTER_DATA_11:
					Log.d("===POSTER_DATA_11===","xujm");
					break;
				case POSTER_DATA_12:
					Log.d("===POSTER_DATA_12===","xujm");
					break;
				case POSTER_DATA_13:
					Log.d("===POSTER_DATA_13===","xujm");
					break;
				default:
					Log.d("===default===","xujm");
					break;
			}
		}
	};

	private final BroadcastReceiver mReceiver = new BroadcastReceiver()
	{
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Log.d("Enter mReceiver ", action);
			if (action.equals(LANRES)) {
				Bundle bundle = intent.getExtras();
				Intent iTrans=new Intent(context, Main.class);
				cmd = bundle.getString(fileBrowser.cmdString);
				lanOpStatus = bundle.getInt(fileBrowser.statusString);
				Log.d("Main onReceive: cmd: ", cmd);
				Log.d("Main onReceive: status: ", String.valueOf(lanOpStatus));
				if (cmd.equals(fileBrowser.lanscan) || cmd.equals(fileBrowser.lanenter))
				{
					Message message;
					if (lanOpStatus == lanOpStatusSucceed)
						message = handler.obtainMessage(POSTER_DATA_0, null);
					else if (cmd.equals(fileBrowser.lanscan))
						message = handler.obtainMessage(POSTER_LANSCAN_FAIL, null);
					else
						message = handler.obtainMessage(POSTER_DATA_1, null);
					handler.sendMessage(message);
				}
			}
		}
	};

	private String getMIMEType(String fName) {
		String type = "*";
		// String fName = f.getName();
		
		String extName = fileBrowser.getExtName(fName);
		Integer resId = fileBrowser.fileImageResIdMap.get(extName);
		if (resId != null) {
			switch (resId) {
			case R.drawable.video:
				type = "video";
				break;
			case R.drawable.jpg:
				type = "image";
				break;
			case R.drawable.audio:
				type = "audio";
				break;
			case R.drawable.apk:
				type="application/vnd.android.package-archive";
				return type;				
			}
		}
		type += "/*";
		return type;
	}

	public void onFileItemClick(String filename) {

		currentFilePath=filename;
		// SharedPreferences mPrefs = getSharedPreferences("FileBrowser", 0);
		// SharedPreferences.Editor ed = mPrefs.edit();
		// ed.putString("currentFilePath", currentFilePath);
		// ed.commit();		
		
		File file = new File(filename);
		setTitle(leftPad + filename);
		Intent intent = new Intent();
		// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction("android.intent.action.VIEW");

		//intent.setDataAndType(Uri.fromFile(file), "image/*");
		intent.setDataAndType(Uri.fromFile(file), getMIMEType(filename));		
		
		startActivityForResult(intent,0);
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		fileBrowser.restoreMe(savedInstanceState);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (currentFilePath==null)
			return;
		
		outState.putString("currentFilePath", currentFilePath);
		Log.d("====onSaveInstanceState===",currentFilePath);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {		
		
		if (requestCode == 0 && resultCode == RESULT_OK && data != null) {
			int currentIndex=data.getIntExtra("currentIndex", -1);
			if (currentIndex>=0)
				fileBrowser.setSelection(++currentIndex);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	public void onDirItemClick(String path) {
		setTitle(leftPad + path);
	}

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		Display display = getWindowManager().getDefaultDisplay();
		int screenWidth = display.getWidth();
		int screenHeight = display.getHeight();
		Log.d("===screenWidth===",String.valueOf(screenWidth)); //800
		Log.d("===screenHeight===",String.valueOf(screenHeight)); //480
		int pixWidth=screenWidth/800;
		int pixHeight=screenHeight/480;
		
		Log.d("===onCreate===", "in");
		setContentView(R.layout.main);
		setTitle(leftPad + "/mnt");

		int marginWidth=screenWidth-350*pixWidth;
		fileBrowser = (FileBrowser) findViewById(R.id.FileBrowser);
		LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(marginWidth, LayoutParams.FILL_PARENT);
		param.setMargins(0, 0, 0, 0);
		fileBrowser.setLayoutParams(param);
		
		fileBrowser.setOnFileBrowserListener(this);

		sizeStr = this.getString(R.string.size);
		dateStr = this.getString(R.string.date);

		LinearLayout layout = (LinearLayout) this
				.findViewById(R.id.LinearLayout1);
		imgFile = new ImageView(layout.getContext());
		
		param = new LinearLayout.LayoutParams(320*pixWidth, 220*pixHeight);
		
		int marginLeft=0;
		param.setMargins(marginLeft, 0, 0, 0);
		imgFile.setLayoutParams(param);
		
		imgFile.setScaleType(ImageView.ScaleType.FIT_XY);
		imgFile.setImageResource(R.drawable.folderpost);
		layout.addView(imgFile, 0);

		int left = 50*pixWidth;
		imgFile.setPadding(left, 5, 0, 0);
		fileSize = (TextView) this.findViewById(R.id.TextViewSize);
		fileSize.setPadding(marginLeft+left, 25, 0, 0);

		fileDate = (TextView) this.findViewById(R.id.TextViewDate);
		fileDate.setPadding(marginLeft+left, 0, 0, 0);

		// LinearLayout.LayoutParams param3 = new LinearLayout.LayoutParams(100,
		// 50);
		// param3.setMargins(300, 50, 0, 0);
		// t.setLayoutParams(param3);

		mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
		mStorageManager.registerListener(mStorageListener);

		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(LANRES);
		registerReceiver(mReceiver, intentFilter);
//		System.out.println("mReceiver, LANRES: " + LANRES);
	}

	public void onDestroy() {
		System.out.println("++++Main++++ onDestroy");
		unregisterReceiver(mReceiver);
		super.onDestroy();
	}

	StorageEventListener mStorageListener = new StorageEventListener() {

		@Override
		public void onStorageStateChanged(String path, String oldState, String newState) {
			Log.i("FileBrowser", "Received storage state changed notification that " + 
				path + " changed state from " + oldState +
				" to " + newState);
			if (newState.indexOf("mounted")>=0)  //unmounted , mounted
			fileBrowser.updateStorageDir();
		}
	};
    
}
